const teamWork = require('../models/teamWork')
const course = require('../models/course')
const users = require('../models/users')
const formidable = require('formidable')
const node_xlsx = require('node-xlsx')
const fs = require('fs')
const send = require('koa-send')
/**
 *
 * 创建团队
 * userID,course,teamName
 * return success or error(已存在) or none(班级没有开始创建团队)
 *
 */
var creatTeam = async(ctx,next)=>{
    let cou = await course.findOne({course:ctx.request.body.course});
    if(cou.isTeam==false){
        return ctx.response.body = {stauts:'none',msg:'班级未开始创建团队'};
    }
    let document = await teamWork.findOne({teamName:ctx.request.body.teamName,course:ctx.request.body.course});
    if(document){
        return ctx.response.body = {stauts:'error',msg:'团队已存在'};
    }
    var menber = [ctx.request.body.userID]

    var teamWorkEntity = new teamWork({
        teamName:ctx.request.body.teamName,
        course:ctx.request.body.course,
        teamMember:menber,
    })

    await teamWorkEntity.save(function(err,doc){
        if(err){
            console.log(err);
        }else{
            console.log(doc);
        }
    })
    return ctx.response.body = {stauts:'success',msg:'成功',teamWorkEntity};
}
/**
 *
 * 退出团队
 * userID，teamName，course
 * retuan success or error（已经没有团队）
 *
 */
var exitTeam = async(ctx,next)=>{
    let document = await teamWork.findOne({teamName:ctx.request.body.teamName,
        course:ctx.request.body.course,teamMember:ctx.request.body.userID});
    if(document){
        await teamWork.findByIdAndUpdate(document._id,{$pull:{teamMember:ctx.request.body.userID}})
        let document1 = await teamWork.findOne({teamName:ctx.request.body.teamName,course:ctx.request.body.course});
        if(document1.teamMember.length==0){
            console.log("团队没有成员，删除团队")
            await teamWork.findByIdAndRemove(document1._id)
        }
        return ctx.response.body = {stauts:'success',msg:'成功'};
    }else{
        return ctx.response.body = {stauts:'error',msg:'你不在该团队里'};
    }
}

/**
 *
 * 提交作业
 * teamName，course,workName,上传的作业文件
 * return success
 * 待测试！！！
 *
 */
var submitWork_team = async(ctx,next)=>{
    var submit = async function(newPath,fields){
        var document = await teamWork.findOne({teamName:fields.teamName,course:fields.course})
        var work = document.work
        for(var i=0;i<work.length;i++){
            if(work[i].workName==fields.workName){
                await teamWork.update({
                    teamName:fields.teamName,
                    course:fields.course,
                    "work.workName":fields.workName
                },{
                    $set:{
                        "work.$.accessory":newPath,
                        "work.$.submitTime":Date.now()
                    }
                });
                if(work[i].endTime<Date.now()){
                    await teamWork.update({
                        teamName:fields.teamName,
                        course:fields.course,
                        "work.workName":fields.workName
                    },{
                        $set:{
                            "work.$.workStatus":-1
                        }
                    });
                }else{
                    await teamWork.update({
                        teamName:fields.teamName,
                        course:fields.course,
                        "work.workName":fields.workName
                    },{
                        $set:{
                            "work.$.workStatus":2
                        }
                    });
                }
            }
        }
        return 'success'
    }
    var fileParse = async function(){
        var form = new formidable.IncomingForm();
            form.encoding = 'utf-8';
            form.uploadDir = './upload/work/';
            form.keepExtensions = true;
            form.maxFieldsSize = 2*1024*1024;
        return new Promise((resolve,reject)=>{
            form.parse(ctx.req,async function(err,fields,files){
                if(err){
                    console.log(form);
                    console.log(err);
                    return;
                }
                var is = await fs.existsSync('./upload/work/'+fields.course+'/'+fields.workName)
                if(!is){
                    await fs.mkdir('./upload/work/'+fields.course+'/'+fields.workName,function(err){
                        if(err){
                            console.log(err);
                        }
                    })
                }
                var fileName = files.fileName.name;
                var isfile = await fs.existsSync('./upload/work/'+fields.course+'/'+fields.workName+'/'+fileName)
                if(isfile){
                    await fs.unlink('./upload/work/'+fields.course+'/'+fields.workName+'/'+fileName,function(err){
                        console.log(err);
                    })
                }
                var newPath = form.uploadDir+fields.course+'/'+fields.workName+'/'+fileName;
                console.log(newPath);
                await fs.renameSync(files.fileName.path,newPath);
                console.log("重命名成功")
                ////////////////////
                var res1=await submit(newPath,fields);
                if(res1=='success')
                resolve("success");
            })
        })
    }
    //////////////
    var res = await fileParse()
    if(res=="success"){
        ctx.response.body = {stauts:'success',msg:'提交成功'};
    }
}

/**
 * 获取团队作业(student)
 * course,teamName,workName
 */
var getWork_stu = async(ctx,next)=>{
    let document = await teamWork.findOne({teamName:ctx.request.body.teamName,course:ctx.request.body.course});
    var work = document.work
    var team = {}
    for(var i=0;i<work.length;i++){
        if(work[i].workName==ctx.request.body.workName){
            team=work[i]
        }
    }
    return ctx.response.body = {stauts:'success',msg:'获取成功',team};
}
/**
 *
 * 获取团队作业(teacher)
 * course,workName
 */
var getWork_tea = async(ctx,next)=>{
    let document = await teamWork.find({course:ctx.request.body.course});
    var menber = new Array()
    for(var i=0;i<document.length;i++){
        var stu = document[i].teamMember
        var stuArr = new Array()
        for(var j=0;j<stu.length;j++){
            let student = await users.findOne({userID:stu[j]})
            stuArr.push(student.userName)
        }
        menber.push(stuArr);
    }
    var team = new Array()
    for(var i=0;i<document.length;i++){
        var work = document[i].work
        for(var j=0;j<work.length;j++){
            if(work[j].workName==ctx.request.body.workName){
                team.push(work[j])
            }
        }
    }
    return ctx.response.body = {stauts:'success',msg:'获取成功',document,menber,team};
}
 /**
  *
    下载团队作业
    workName，course，teamName

  */
  var download_stu = async(ctx,next)=>{
    var document = await teamWork.findOne({teamName:ctx.params.teamName,course:ctx.params.course})
    var work = document.work
    for(var i=0;i<work.length;i++){
        if(work[i].workName==ctx.params.workName){
            var fileName = work[i].accessory.substring(work[i].accessory.lastIndexOf("/")+1,work[i].accessory.length);
            var path = work[i].accessory;
            ctx.attachment(fileName);
            await send(ctx, path);
        }
    }
    ctx.response.body = {stauts:'success',msg:'成功'};
 }
  /**
  *
  * 评分
  * workName，course，teamName,score,evaluate(可以为空)
  *
  */
  var setTeamScore = async(ctx,next)=>{
    var document = await teamWork.findOne({teamName:ctx.request.body.teamName,course:ctx.request.body.course})
    var work = document.work
    for(var i=0;i<work.length;i++){
        if(work[i].workName==ctx.request.body.workName){
            if(work[i].accessory==""){
                return ctx.response.body = {stauts:'error',msg:'学生未交作业'};
            }
        }
    }
    await teamWork.update({
        teamName:ctx.request.body.teamName,
        course:ctx.request.body.course,
        "work.workName":ctx.request.body.workName
    },{
        $set:{
            "work.$.score":ctx.request.body.score,
            "work.$.evaluate":ctx.request.body.evaluate
        }
    });
    return ctx.response.body = {stauts:'success',msg:'成功'};
 }
module.exports = {
    'POST /teamWork/creatTeam': creatTeam,
    'POST /teamWork/exitTeam': exitTeam,
    'POST /teamWork/submitWork_team': submitWork_team,
    'POST /teamWork/getWork_stu': getWork_stu,
    'POST /teamWork/getWork_tea': getWork_tea,
    'GET /teamWork/download_stu/:workName/:course/:teamName': download_stu,
    'POST /teamWork/setTeamScore': setTeamScore,
}
